//
//  TinyRadioGroupViewCell.m
//  TinyRadioGroup
//
//  Created by kingdomrain on 2020/6/20.
//  Copyright © 2020 sunline. All rights reserved.
//

#import "TinyRadioGroupViewCell.h"
#import "TinyRadioGroupConst.h"
#import <TinyUI/TinyUI.h>
#import "UILabel+TinyTextAlign.h"

@interface TinyRadioGroupViewCell()
@property(nonatomic,strong)UIImageView *radioView;
@property(nonatomic,strong)UILabel *title;
@property(nonatomic,strong)UILabel *indexLabel;
@property(nonatomic,strong)UIView *itemCentent;   //需要把radio，index，caption字段放在一个view上
@property(nonatomic,strong)UIView *line;
//
@property(nonatomic,copy)NSString *type;
@property(nonatomic,copy)NSString *itemValue;  //当前值

//RadioGroup支持的样式
@property(nonatomic,copy)NSString *dependenciesUri;
@property(nonatomic,assign)CGFloat width;
@property(nonatomic,assign)CGFloat height;
@property(nonatomic,assign)CGFloat radioWidth;
@property(nonatomic,assign)CGFloat radioHeight;
@property(nonatomic,copy)NSString *checkImgPath;
@property(nonatomic,copy)NSString *unCheckImgPath;
@property(nonatomic,copy)NSString *titleColor;
@property(nonatomic,assign)CGFloat titleFontSize;
//@property(nonatomic,assign)CGFloat radioMargin;
@property(nonatomic,copy)NSString *titleSelectColor;
@property(nonatomic,copy)NSString *cellBackgroundColor;
@property(nonatomic,assign)CGFloat dividerHeight;
@property(nonatomic,assign)CGFloat dividerMargin;
@property(nonatomic,copy)NSString *dividerColor;
@property(nonatomic,assign)CGFloat radioDrawablePadding;
@property(nonatomic,strong)NSArray *itemMargin;
@property(nonatomic,strong)NSArray *itemPadding;
@property(nonatomic,assign)CGFloat itemBorderRadius;
@property(nonatomic,copy)NSString *itemBackgroundColor;
@property(nonatomic,copy)NSString *itemHighlightedColor;
@property(nonatomic,assign)CGFloat itemIndexSpacing;

@end

@implementation TinyRadioGroupViewCell

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self setUpUI];
        self.itemValue = kTinyRadioGroupRadioUnCheckStatus;  //默认没有选中
    }
    return self;
}

-(void)setUpUI{
    _itemCentent = [[UIView alloc] initWithFrame:CGRectZero];
    [self.contentView addSubview:_itemCentent];
    
    _radioView = [[UIImageView alloc] initWithFrame:CGRectZero];
    _radioView.backgroundColor = [UIColor clearColor];
    _radioView.contentMode = UIViewContentModeScaleToFill;
    [_itemCentent addSubview:_radioView];
    
    _indexLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    _indexLabel.backgroundColor = [UIColor clearColor];
    _indexLabel.numberOfLines = 0;
    [_itemCentent addSubview:_indexLabel];
    
    _title = [[UILabel alloc] initWithFrame:CGRectZero];
    _title.backgroundColor = [UIColor clearColor];
    _title.numberOfLines = 0;
    _title.lineBreakMode = NSLineBreakByCharWrapping;
    [_itemCentent addSubview:_title];
        
    _line = [[UIView alloc] initWithFrame:CGRectZero];
    [self.contentView addSubview:_line];
}

-(void)drawRect:(CGRect)rect{
    if (_cellBackgroundColor) {
        self.contentView.backgroundColor = [UIColor tyColorWithHex:_cellBackgroundColor];
    }
    if (_titleFontSize) {
        _title.font = [UIFont systemFontOfSize:_titleFontSize];
        _indexLabel.font = [UIFont systemFontOfSize:_titleFontSize];
    }
    if (_dividerHeight && _dividerMargin) {
        _line.frame = CGRectMake(_dividerMargin, self.frame.size.height-_dividerHeight,self.frame.size.width -2 *_dividerMargin, _dividerHeight);
    }
    if(_dividerColor){
        _line.backgroundColor = [UIColor tyColorWithHex:_dividerColor];
    }
    //选中和未选中item的背景色和文字颜色
    if ([self.itemValue isEqualToString:kTinyRadioGroupRadioUnCheckStatus]) {
        self.itemCentent.backgroundColor = [UIColor tyColorWithHex:_itemBackgroundColor];
        if (_titleColor) {
            _title.textColor = [UIColor tyColorWithHex:_titleColor];
            _indexLabel.textColor = [UIColor tyColorWithHex:_titleColor];
        }
    }
    else if ([self.itemValue isEqualToString:kTinyRadioGroupRadioCheckStatus]){
        self.itemCentent.backgroundColor = [UIColor tyColorWithHex:_itemHighlightedColor];
        if (_titleSelectColor) {
            _title.textColor = [UIColor tyColorWithHex:_titleSelectColor];
            _indexLabel.textColor = [UIColor tyColorWithHex:_titleSelectColor];
        }
    }
    //圆角
    if(_itemBorderRadius){
        self.itemCentent.layer.cornerRadius = _itemBorderRadius;
        self.itemCentent.layer.masksToBounds = YES;
    }
    [_indexLabel topAlignment];
    [_title topAlignment];
}

-(void)layoutSubviews{
    //计算item content的大小
    CGFloat itemContentX = [_itemMargin[3] floatValue];
    CGFloat itemContentY = [_itemMargin[0] floatValue];
    CGFloat itemContentWidth = self.contentView.frame.size.width - [_itemMargin[1] floatValue] - [_itemMargin[3] floatValue];
    CGFloat itemContentHeight = self.contentView.frame.size.height - [_itemMargin[0] floatValue] - [_itemMargin[2] floatValue];
    _itemCentent.frame = CGRectMake(itemContentX,itemContentY,itemContentWidth,itemContentHeight);
    //计算内边距，获取真正绘制的CGRect
    CGFloat drawContentX = [_itemPadding[3] floatValue];
    CGFloat drawContentY = [_itemPadding[0] floatValue];
    CGFloat drawContentWidth = itemContentWidth - [_itemPadding[1] floatValue] - [_itemPadding[3] floatValue];
    CGFloat drawContentHeight = itemContentHeight - [_itemPadding[0] floatValue] - [_itemPadding[2] floatValue];
    CGFloat paddingRight = [_itemPadding[0] floatValue];
    //根据_indexLabel.text的内容和设置的字号计算indexLabel的宽度
    CGFloat indexWidth = [self widthForString:_indexLabel.text fontSize:_titleFontSize andHeight:itemContentHeight];
    CGFloat radioImageViewY = (drawContentHeight - _radioHeight) / 2;
    CGFloat textHeight = drawContentHeight;
    
    if (_type != nil && [_type isEqualToString:kTinyRadioGroupAttibutTitlePositionValueLeft]) {
        CGFloat textWidth;
        if ([_itemValue isEqualToString:@"1"]) {
            textWidth = drawContentWidth - (indexWidth + _itemIndexSpacing) - (_radioWidth +_radioDrawablePadding );
        }
        else{
            textWidth = drawContentWidth - (indexWidth + _itemIndexSpacing) - _radioDrawablePadding;
        }
        _indexLabel.frame = CGRectMake(drawContentX, drawContentY ,indexWidth , textHeight);
        _title.frame = CGRectMake(drawContentX + indexWidth + _itemIndexSpacing , drawContentY ,textWidth, textHeight);
        _radioView.frame = CGRectMake(itemContentWidth - _radioWidth - paddingRight , drawContentY + radioImageViewY, _radioWidth, _radioHeight);
    }
    else if(_type != nil && [_type isEqualToString:kTinyRadioGroupAttibutTitlePositionValueRight]){
        _radioView.frame = CGRectMake(drawContentX, drawContentY + radioImageViewY, _radioWidth, _radioHeight);
        _indexLabel.frame = CGRectMake(drawContentX + _radioWidth + _radioDrawablePadding , drawContentY , indexWidth , textHeight);
        CGFloat textWidth = drawContentWidth - _radioWidth - _radioDrawablePadding - indexWidth - _itemIndexSpacing;
        _title.frame = CGRectMake(drawContentX + _radioWidth + _radioDrawablePadding + indexWidth + _itemIndexSpacing , drawContentY ,textWidth, textHeight);
    }
}

-(void)setStyle:(id)param withValue:(id)value{
    if([param isEqualToString:kTinyRadioGroupStyleNameDependenciesUri]){
        _dependenciesUri = value;
    }
    else if ([param isEqualToString:kTinyRadioGroupStyleNameWidth]){
        _width = [value floatValue];
    }
    else if ([param isEqualToString:kTinyRadioGroupStyleNameHeight]){
        _height = [value floatValue];
    }
    else if ([param isEqualToString:kTinyRadioGroupStyleNameRadioWidth]){
        _radioWidth = [value floatValue];
    }
    else if ([param isEqualToString:kTinyRadioGroupStyleNameRadioHeight]){
        _radioHeight = [value floatValue];
    }
    else if ([param isEqualToString:kTinyRadioGroupStyleNameCheckImg]){
        _checkImgPath = value;
    }
    else if ([param isEqualToString:kTinyRadioGroupStyleNameUnCheckImg]){
        _unCheckImgPath = value;
    }
    else if ([param isEqualToString:kTinyRadioGroupStyleNameTitleColor]){
        _titleColor = value;
    }
    else if ([param isEqualToString:kTinyRadioGroupStyleNameTextFont]){
        _titleFontSize = [value floatValue];
    }
//    else if ([param isEqualToString:kTinyRadioGroupStyleNameRadioMargin]){
//        _radioMargin = [value floatValue];
//    }
    else if ([param isEqualToString:kTinyRadioGroupStyleNameTitleSelectColor]){
        _titleSelectColor = value;
    }
    else if ([param isEqualToString:kTinyRadioGroupStyleNameBackgroundColor]){
        //背景色支持主题
        NSString *themeBackgroundColor = [TinyTheme configWithType:@0 param:(NSString *)value];
        _cellBackgroundColor = themeBackgroundColor;
    }
    else if ([param isEqualToString:kTinyRadioGroupStyleNameDividerHeight]){
        _dividerHeight = [value floatValue];
    }
    else if ([param isEqualToString:kTinyRadioGroupStyleNameDividerMargin]){
        _dividerMargin = [value floatValue];
    }
    else if ([param isEqualToString:kTinyRadioGroupStyleNameDividerColor]){
        _dividerColor = value;
    }
    else if ([param isEqualToString:kTinyRadioGroupStyleNameRadioDrawablePadding]){
        _radioDrawablePadding = [value floatValue];
    }
    else if ([param isEqualToString:kTinyRadioGroupStyleNameItemMargin]){
        _itemMargin = [(NSString *)value componentsSeparatedByString:@" "];
    }
    else if ([param isEqualToString:kTinyRadioGroupStyleNameItemPadding]){
        _itemPadding = [(NSString *)value componentsSeparatedByString:@" "];
    }
    else if ([param isEqualToString:kTinyRadioGroupStyleNameItemBorderRadius]){
        _itemBorderRadius = [value floatValue];
    }
    else if ([param isEqualToString:kTinyRadioGroupStyleNameItemBackgroundColor]){
        _itemBackgroundColor = value;
    }
    else if ([param isEqualToString:kTinyRadioGroupStyleNameItemHighlightedColor]){
        _itemHighlightedColor = value;
    }
    else if ([param isEqualToString:kTinyRadioGroupStyleNameItemIndexSpacing]){
        _itemIndexSpacing = [value floatValue];
    }
}

#pragma mark -- Public Method
-(void)setCellStyleType:(NSString *)type withStyleSheet:(NSDictionary *)style{
    _type = type;
    for(NSString *key in style.allKeys){
        NSString *obj = style[key];
        [self setStyle:key withValue:obj];
    }
}

-(void)refresh:(NSDictionary *)data{
    NSString *value = data[kTinyRadioGroupRadioValue];
    NSString *caption = data[kTinyRadioGroupRadioCaption];
    NSString *indexString = data[kTinyRadioGroupRadioIndex];
    
    if ([value isEqualToString:kTinyRadioGroupRadioUnCheckStatus]) {
        [self setRadioViewImageWithPath:_unCheckImgPath];
    }
    else if ([value isEqualToString:kTinyRadioGroupRadioCheckStatus]){
        [self setRadioViewImageWithPath:_checkImgPath];
    }
    _itemValue = value;
    _indexLabel.text = indexString;
    _title.text = caption;
    [self setNeedsDisplay];
}

#pragma mark -- Private Method
/// 设置radioview的iamge，如果是path是空，清空当前radioview的iamge。
/// @param imagePath image的路径
-(void)setRadioViewImageWithPath:(NSString *)imagePath{
    if (imagePath == nil) {
        self.radioView.image = nil;
    }
    else{
        __weak typeof(self)weakself = self;
        [self tiny_loadImageWithPath:imagePath dependenceUri:_dependenciesUri hander:^(NSData * _Nullable data, NSError * _Nullable error) {
            if (data) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if([data isKindOfClass:[NSData class]]){
                        [weakself.radioView setImage:[UIImage imageWithData:data]];
                    }
                    else if([data isKindOfClass:[UIImage class]]){
                        [weakself.radioView setImage:(UIImage *)data];
                    }
                });
            }
        }];
    }
}

-(CGFloat)widthForString:(NSString *)value fontSize:(CGFloat)fontSize andHeight:(CGFloat)height
{
    CGSize strSize = CGSizeMake(CGFLOAT_MAX, height);
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]};
    CGFloat stringWidth = 0;
    if (value) {
        CGRect rect = [value boundingRectWithSize:strSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
        stringWidth = rect.size.width;
    }
    return stringWidth;
}

-(float)heightForString:(NSString *)value fontSize:(float)fontSize andWidth:(float)width
{
    CGSize strSize = CGSizeMake(width, CGFLOAT_MAX);
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]};
    CGFloat stringHeight = 0;
    if (value) {
        CGRect rect = [value boundingRectWithSize:strSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
        stringHeight = rect.size.height;
    }
    return stringHeight;
}

@end
